package mygw.jtthink.com.Utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtil {
    //jwt 的过期时间
    private final static Long TokenAutoTTL=10L;//秒
    public final static Long TokenRedisExpire=40*1000L;//毫秒

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //生成token
    public String genToken(String uname){
        Map<String,Object> claims=new HashMap<>();
        claims.put("username",uname);
        claims.put("version",System.currentTimeMillis());
       return  Jwts.builder()
                .setClaims( claims )
                .signWith( SignatureAlgorithm.HS256, "123456" )
                .compact();
    }
    public Long setToken(String uname,String token){
        ValueOperations<String,String> v= stringRedisTemplate.opsForValue();
        String tokenKey="token_"+uname;
        v.set(tokenKey,token,TokenUtil.TokenRedisExpire, TimeUnit.MILLISECONDS);
        return stringRedisTemplate.getExpire(tokenKey);
    }
    //检查token是否已经生成
    public Map<String,Object> checkToken(String uname){
        ValueOperations<String,String> v= stringRedisTemplate.opsForValue();
        String tokenKey="token_"+uname;
        String getToken=v.get(tokenKey);
        if(getToken!=null){
            return new HashMap<String,Object>(){
                {
                    put("token",getToken);
                    put("expire",stringRedisTemplate.getExpire(tokenKey));
                }
            };
        }
        return null;
    }

    //判断token是否存在 以及合法
    public boolean isExistToken(String uname,String token,boolean autottl){
        ValueOperations<String,String> v= stringRedisTemplate.opsForValue();
        String tokenKey = "token_"+uname;
        String getToken=v.get("token_"+uname);
        if(getToken!=null && getToken.equals(token)){
            if(autottl && stringRedisTemplate.getExpire(tokenKey)<=TokenAutoTTL){
                //自动需求
                stringRedisTemplate.expire(tokenKey,TokenRedisExpire,TimeUnit.MILLISECONDS);
            }
            return true;
        }
        return false;
    }
}
